//
//  STPushVC.swift
//  Demo-04-TabBar的尝试
//
//  Created by 苏统世 on 16/5/9.
//  Copyright © 2016年 SuTon. All rights reserved.
//

import UIKit

class STPushVC: UIViewController {

    /// 初始化长度Label文本
    private let textMaxCount = 25
    
    /// toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()
    /// STKeyBoardView
    private lazy var customKeyBoard:STKeyBoardView = {
        let keyBoard = STKeyBoardView()
        keyBoard.textView = self.customTextView
        return keyBoard
    }()
    private lazy var customTextView:STCustomTextView = {
        let textView = STCustomTextView()
        textView.placeholderText = "请输入"// 有默认
        textView.font = UIFont.systemFontOfSize(18.0)
        textView.backgroundColor = UIColor.whiteColor()
        textView.alwaysBounceVertical=true
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.delegate = self
        
        return textView
    }()
    
    private var closeKeyBoadrTime:NSTimeInterval = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor=UIColor.redColor()
        /// 设置导航栏
        setupNavigation()
        /// 设置UI
        setupUI()
        /// 设置工具栏
        setupToolBar()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyBoardChangeFrame:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 键盘改变的方法
    func willChangeFrame(notification: NSNotification) {
//        STPrint(items: "notification: \(notification)")
        
        // 获取键盘动画的时间
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        // 获取最终的frame值
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 计算toolBar底部的间距
        let bottomMargin = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            // 更新约束
            self.toolBar.snp_updateConstraints { (make) -> Void in
                make.bottom.equalTo(self.view).offset(bottomMargin)
            }
            
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func keyBoardChangeFrame(keyBoardInfo:NSNotification){
//        STPrint(items: keyBoardInfo.userInfo)
        /*
            [
                UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 667}, {375, 258}},
                UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 409}, {375, 258}},
        
                UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {375, 258}},
        
                UIKeyboardAnimationDurationUserInfoKey: 0.25,
        
                UIKeyboardCenterEndUserInfoKey: NSPoint: {187.5, 538},
                UIKeyboardCenterBeginUserInfoKey: NSPoint: {187.5, 796},
            ]
        */
        /// 获取键盘打开、关闭时间
        let duration = keyBoardInfo.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        closeKeyBoadrTime = duration
        let endFrame = keyBoardInfo.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        let bottomMargin = -(UIScreen.mainScreen().bounds.height - endFrame.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(self.view).offset(bottomMargin)
            })
            self.view.layoutIfNeeded()
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        customTextView.becomeFirstResponder()
    }
    /// 设置UI
    private func setupUI(){
        self.view.addSubview(customTextView)
        self.view.addSubview(textCheckLabel)
        self.view.addSubview(toolBar)
//        toolBar.backgroundColor=UIColor.blackColor()
        
        customTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        textCheckLabel.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(self.view).offset(-3)
            make.bottom.equalTo(toolBar.snp_top).offset(-3)
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // MARK: - 设置navigationItem
    private func setupNavigation(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickCancleButton")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickSendButton")
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitleView()
    }

    private func setupTitleView(){
        let basicTitle = "发微博"
        
        if let userName = STUserAccountViewModel.shareManager.userAccount?.screen_name{
            
            let totalTitle = basicTitle+"\n"+userName
            let labelView = UILabel()
            labelView.font = UIFont.systemFontOfSize(13)
            let labelAttr = NSMutableAttributedString(string: totalTitle)
            let rangeUserName = (totalTitle as NSString).rangeOfString(userName)
            
            labelAttr.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: rangeUserName)
            labelAttr.addAttribute(NSFontAttributeName, value:UIFont.systemFontOfSize(11), range: rangeUserName)
            labelView.attributedText=labelAttr
//            labelView.text = totalTitle
            labelView.numberOfLines = 0
            labelView.textAlignment=NSTextAlignment.Center
            labelView.sizeToFit()
            
            navigationItem.titleView=labelView

        }else{
            navigationItem.title = basicTitle
        }
    }
    // MARK: - TitleView Button Action
    @objc private func didClickCancleButton(){
        customTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func didClickSendButton(){
        STPrint(items: "点击了发送按钮")
        let sendText = customTextView.getEmoticonNameText()
        if textMaxCount < sendText.characters.count {
            STPrint(items: "输入文本过长！")
            return
        }
        STDataViewModel.shareManager.sendMessage(sendText) { (error) -> () in
            if error != nil {
                STPrint(items: "发布失败")
            }
            STPrint(items: "发布成功")
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
                self.didClickCancleButton()
            }
        } 
    }
    /// 设置toolBar
    private func setupToolBar() {
        let itemSettings = [
            ["imageName": "compose_toolbar_picture", "action": "picture"],              // 发送图片
            ["imageName": "compose_trendbutton_background", "action": "trend"],         // #
            ["imageName": "compose_mentionbutton_background", "action": "mention"],     // @
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],   // 表情
            ["imageName": "compose_add_background", "action": "add"]                    // +
        ]
        /// 实例化
        toolBar.items = [UIBarButtonItem]()
        for dict in itemSettings{
            
            toolBar.items?.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: Selector(dict["action"]!), touchStype: UIControlEvents.TouchUpInside))
            
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        toolBar.items?.removeLast()
    
    }
    // MARK: - ToolBar Button Action
    @objc private func picture() {
        STPrint(items: "发送图片")
    }
    
    @objc private func trend() {
        STPrint(items: "#")
    }
    
    @objc private func mention() {
        STPrint(items: "@")
    }
    
    @objc private func emoticon(button:UIButton) {
        STPrint(items: "表情")
        // 在弹出前, inputView == nil,就弹出系统键盘, inputView != nil, 就使用设置的键盘

        var emoticonImage:UIImage?
        
        if customTextView.inputView == nil{
            customTextView.inputView = customKeyBoard
            emoticonImage = UIImage(named: "compose_keyboardbutton_background")
        }else{
            customTextView.inputView = nil
            emoticonImage = UIImage(named: "compose_emoticonbutton_background")
        }
        button.setImage(emoticonImage, forState: UIControlState.Normal)
        
        self.customTextView.resignFirstResponder()
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(self.closeKeyBoadrTime*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.customTextView.becomeFirstResponder()
        }

        
    }
    
    @objc private func add() {
        STPrint(items: "+")
    }
    
    /// 懒加载 监测文本字数 Label
    private lazy var textCheckLabel:UILabel = {
        let cLabel = UILabel()
        cLabel.text = String(self.textMaxCount)
        cLabel.font = UIFont.systemFontOfSize(10)
        cLabel.textColor = UIColor.darkGrayColor()
        cLabel.sizeToFit()
        return cLabel
    }()
}
// MARK: - 代理方法
extension STPushVC: UITextViewDelegate {
    // 文字改变
    func textViewDidChange(textView: UITextView) {
        STPrint(items: "文字改变: \(textView.text)")
        
        let textString = textView.getEmoticonNameText()
        
        STPrint(items: "textString:\(textString)")
        
        // 有文字,rightBarButtonItem可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}



